<?php
	$cur_page_ver="1.0a";
	$this_page="profilesearch";
	$this_title="Search";
	$per_page=25;
	require_once('includes/global.php');
	if(isset($_GET['submit']) && $_GET['submit']==='Search')
	{
		$search=isset($_GET['search'])?$_GET['search']:null;
		$smarty->assign('search',$search);
		$page=isset($_GET['page'])?$_GET['page']:1;
		$start_at=$page*$per_page-$per_page;
		if($search===null)
		{
			displayAllUsers();
			break;
		}
		else
		{
			//Maybe use explode later using quotes first then spaces
			while(strlen($search)>0)
			{
				$next=strstr($search,' ');
				//echo $next;
				$next==false?$item=$search:$item=substr($search,0,strlen($search)-strlen($next));
				strlen($parsedSearch)==0?$parsedSearch="`UN` LIKE '%".$item."%' OR `name` LIKE '%".$item."%'":$parsedSearch.="OR `UN` LIKE '%".$item."%' OR `name` LIKE '%".$item."%' ";
				$search=substr($next,1);
				$item==$search?$search='':null;
			}
//			echo $parsedSearch;
//			echo "SELECT users.UID,logged,UN,name,location from users LEFT JOIN profiles on users.UID=profiles.UID WHERE $parsedSearch";
			$result=$dbcon->query("SELECT users.UID,logged,UN,name,location from users LEFT JOIN profiles on users.UID=profiles.UID WHERE $parsedSearch");
			if(isset($result['UN']))
			{
				$result=array('0' => $result);
			}
			$smarty->assign('num_results',count($result));
			$total_pages=!(count($result)%$per_page==0)?(int)(count($result)/$per_page+1):(count($result)/$per_page);
			$result=$dbcon->query("SELECT users.UID,logged,UN,name,location from users LEFT JOIN profiles on users.UID=profiles.UID WHERE $parsedSearch LIMIT {$start_at},{$per_page}");
			
			//$where= "UN LIKE '<search text>' OR name LIKE '<search text>'";
			
			if(isset($result['UN']))
			{
				$result=array('0' => $result);
			}
			$smarty->assign('total_pages',$total_pages+1);
			$smarty->assign('page',$page);
			$smarty->assign('search_result',$result);
			$smarty->display('header.tpl');
			$smarty->display('search.tpl');
			$smarty->display('footer.tpl');
		}
	}
?>